package com.iot08.api.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.iot08.common.constant.Const;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.HttpReq;
import com.iot08.common.utils.RandomUtil;
import com.iot08.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.*;

/**
 * 瑞集物联网卡工具类
 */
@Slf4j
public class RuiJiIOTUtil {

    /*           ====瑞集物联网卡====            */
    private static final String RJ_USEID = "129";
    private static final String RJ_APP_Key = "cd54cf06e81fc226b3c65e0e3719b3db";

    //查询白名单
    private static final String RJ_WHITELIST_URL = "http://api.ruijiiot.com.cn:32040/api/v1/whiteList";
    /*
    添加/删除白名单 POST
    每月只能调用一次删除白名单动作
    {
        "code": -1,
        "data": [],
        "msg": "本月删除白名单号码次数已达上限，本次业务办理失败"
    }
     */
    private static final String RJ_DO_WHITELIST_URL = "http://api.ruijiiot.com.cn:32040/api/v1/doWhiteList";

    /**
     * 查询物联卡白名单
     *
     * @param iccid
     * @time: 2023/12/2210:09
     * @author: weichao
     * @version 1.0
     */
    public static Object queryRJCardWhiteList(String iccid) {
        //秒级时间戳
        Long times = DateUtil.nowTimestampToLong();
        String url = String.format("%s?userId=%s&times=%s&sign=%s&cardno=%s", RJ_WHITELIST_URL, RJ_USEID, times, getSignWithTimes(times), iccid);
        String result = HttpReq.sendGet(url);
        String activeProfile = SpringContextUtil.getActiveProfile();
        if("dev".contains(activeProfile) || "local".contains(activeProfile)){
            //测试环境 打印日志
            log.info("瑞集的物联网卡 查询白名单返回数据 :iccid:{} result:{} url:{}", iccid, result, url);
        }
        if (StringUtil.isNotBlank(result)) {
            JSONObject resultJson = JSON.parseObject(result);
            if (0 == resultJson.getInteger("code")) {
                return resultJson.getJSONArray("data");
            }else if (-2 == resultJson.getInteger("code")) {
                // 卡号不存在 , 可能不是物联网卡
                return resultJson.getString("msg");
            }else{
                log.error("瑞集 查询物联卡白名单 失败:{}", result);
                return resultJson.getString("msg");
            }
        }
        log.info("queryRJCardWhiteList is fail. iccid = {} result={}", iccid, result);
        return "未知原因";
    }

    /**
     * 添加 或 删除 白名单
     * @param iccid
     * @param phone
     * @time: 2023/12/2210:14
     * @author: weichao
     * @version 1.0
     */
    public static Object doRJCardWhiteList(String iccid, String phone, boolean isAdd) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", RJ_USEID);
        //秒级时间戳
        Long times = DateUtil.nowTimestampToLong();
        params.put("times", times);
        params.put("sign", getSignWithTimes(times));
        params.put("cardno", iccid);
        params.put("phone", phone);
        if (isAdd) {
            params.put("operType", 1);
        }else{
            params.put("operType", 4);
        }

        String result = HttpReq.sendPostJson(RJ_DO_WHITELIST_URL, JSON.toJSONString(params));
        String activeProfile = SpringContextUtil.getActiveProfile();
        if("dev".contains(activeProfile) || "local".contains(activeProfile)){
            //测试环境 打印日志
            log.info("瑞集的物联网卡 操作:isAdd:{} 白名单返回数据 :iccid:{} result:{} params:{}",isAdd , iccid, result, params);
        }
        if (StringUtil.isNotBlank(result)) {
            JSONObject resultJson = JSON.parseObject(result);
            if (Const.INT_0.equals(resultJson.getInteger("code"))) {
                return true;
            }else{
                return resultJson.getString("msg");
            }
        }
        return "未知错误";
    }

    /**
     * 签名加密
     *
     * @param times
     * @time: 2023/12/22 17:43
     * @author: weichao
     * @version 1.0
     */
    public static String getSignWithTimes(Long times) {
        String tempStr = String.format("userId=%s&apikey=%s&times=%s", RJ_USEID, RJ_APP_Key, times);
        String sign = DigestUtils.md5Hex(tempStr).toUpperCase();
        return sign;

    }
//    /**
//     * 签名加密
//     *
//     * @param paramValues
//     * @time: 2023/12/22 17:43
//     * @author: weichao
//     * @version 1.0
//     */
//    public static String sign(Map<String, Object> paramValues) {
//        try {
//            StringBuilder sb = new StringBuilder();
//            List<String> paramNames = new ArrayList<String>(paramValues.size());
//            paramNames.addAll(paramValues.keySet());
//            Collections.sort(paramNames);
//            sb.append(Const.RJ_APP_SECRET);
//            for (String paramName : paramNames) {
//                sb.append(paramName).append(paramValues.get(paramName).toString());
//            }
//            sb.append(Const.RJ_APP_SECRET);
//            byte[] sha1Digest = getSHA1Digest(sb.toString());
//            String rst = byte2hex(sha1Digest);
//            log.info("calc sign, param: {}, sign: {}", sb.toString(), rst);
//            return rst;
//        } catch (IOException e) {
//            log.error("sign error", e);
//            return null;
//        }
//    }
//
//    public static byte[] getSHA1Digest(String data) throws IOException {
//        byte[] bytes = null;
//        try {
//            MessageDigest md = MessageDigest.getInstance("SHA-1");
//            bytes = md.digest(data.getBytes("UTF-8"));
//        } catch (GeneralSecurityException gse) {
//            throw new IOException(gse);
//        }
//        return bytes;
//    }
//
//    /**
//     * 二进制转十六进制字符串
//     *
//     * @param bytes
//     * @return
//     */
//    public static String byte2hex(byte[] bytes) {
//        StringBuilder sign = new StringBuilder();
//        for (int i = 0; i < bytes.length; i++) {
//            String hex = Integer.toHexString(bytes[i] & 0xFF);
//            if (hex.length() == 1) {
//                sign.append("0");
//            }
//            sign.append(hex.toUpperCase());
//        }
//        return sign.toString();
//    }

}
